package com.lineng.controller;

import java.io.File;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lineng.service.GeneralizeService;

@Controller
public class FileController {

	@Autowired
	GeneralizeService generalizeService;

	private String uploadPath = null;

	private String filePathString = null;

	private List<String> pathList = new ArrayList<String>();

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> uploadFile(HttpServletRequest request, MultipartFile file, String fileName,
			String fileId) throws UnknownHostException {
		boolean b = false;
		String ip = request.getServerName();
		String path1 = request.getContextPath();
		String basePath = request.getScheme() + "://" + ip + ":" + request.getServerPort() + path1 + "/";
		Map<String, String> location = new HashMap<String, String>();
		// 获取当前时间
		Date time = new Date();
		// 获取当前项目路径
		ServletContext sc = request.getSession().getServletContext();
		filePathString = sc.getRealPath("/") + "upload/" + fileName + ("/") + fileId + ("/");
		// 上传位置
		uploadPath = filePathString + time.getTime() + file.getOriginalFilename().replace(" ", "");
		// 返回给前端的路径
		String path = basePath + "upload/" + fileName + ("/") + fileId + ("/") + time.getTime()
				+ file.getOriginalFilename().replace(" ", "");
		// 设定文件保存的目录
		if (file != null) {
			try {
				b = saveFile(file, uploadPath);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (b == true) {
			location.put("location", path);
			location.put("status", "200");
			return location;
		} else {
			location.put("status", "0");
			return location;
		}

	}

	private boolean saveFile(MultipartFile file, String path) throws Exception {
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				File filepath = new File(path);
				if (!filepath.exists())
					filepath.mkdirs();
				// 文件保存路径
				String Url = path;
				// 转存文件
				file.transferTo(new File(Url));
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
		}
		return false;
	}

	/**
	 * 获取富文本框html
	 * 
	 * @param htmlString
	 * @param request
	 */

	@RequestMapping(value = "/html", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public void deletePath(String htmlString, HttpServletRequest request) {
		List<String> path1 = new ArrayList<String>();
		List<String> htmlpath = GetHtmlImageSrcList(htmlString);
		if (htmlpath != null && !htmlpath.isEmpty()) {
			String path = null;
			// 获取当前项目路径
			ServletContext sc = request.getSession().getServletContext();
			// 上传位置
			String projectPath = sc.getRealPath("/");
			for (int i = 0; i < htmlpath.size(); i++) {
				if (htmlpath.get(i).indexOf("lineng/upload") != -1) {
					path = projectPath
							+ htmlpath.get(i).substring(htmlpath.get(i).indexOf("upload"), htmlpath.get(i).length());
					path1.add(path);
				}
			}
			if (filePathString != null && !path1.isEmpty()) {
				pathList = getFilePath(filePathString);
				if (pathList != null) {
					List<String> filepath = getDiffElementUseMap(path1, pathList);
					for (int i = 0; i < filepath.size(); i++) {
						File file = new File(filepath.get(i));
						if (file.length() > 0) {
							file.delete();
						}
					}
					filepath.clear();
					pathList.clear();
				}
			}
		}
		htmlpath.clear();
	}

	/**
	 * 获取HTML文件里面的IMG标签的SRC地址
	 * 
	 * @param htmlText
	 *            带html格式的文本
	 */
	public static List<String> GetHtmlImageSrcList(String htmlText) {
		List<String> imgSrc = new ArrayList<String>();
		Matcher m = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(htmlText);
		while (m.find()) {
			imgSrc.add(m.group(1));
		}
		return imgSrc;
	}

	public List<String> getDiffElementUseMap(List<String> list1, List<String> list2) { // 获得两个list中的不同元素，map方法
																						//  
		final Integer flagUnique = 1;// 无重复字符串的键值 
		// 利用map中不能有重复元素的特点
		Map<String, Integer> map = new HashMap<String, Integer>(list1.size() + list2.size());
		List<String> diffList = new ArrayList<String>();// 用于保存两个list中不同的元素
		for (String string : list1) {
			map.put(string, flagUnique);// 先将list1中元素复制到map中保存
		}
		for (String string : list2) {
			Integer key = map.get(string);// 获得键值
			if (key != null) {// 如果map中已经存在该元素，说明list1中存在该元素，那么将其key加1
				map.put(string, ++key);
				continue;
			} else {// 如果不存在，则放入map中
				map.put(string, flagUnique);
			}
		}
		for (Map.Entry<String, Integer> entry : map.entrySet()) {
			if (entry.getValue() == flagUnique)// 在map中，键值为flagUnique的元素即为无重复的元素s
			{
				diffList.add(entry.getKey());
			}
		}
		return diffList;
	}

	/**
	 * 获取服务器文件
	 * 
	 * @param path
	 * @return
	 */
	public List<String> getFilePath(String path) {
		File file = new File(path); // 获取其file对象
		File[] fs = file.listFiles(); // 遍历path下的文件和目录，放在File数组中
		if (fs.length > 0) {
			for (File f : fs) { // 遍历File[]数组
				if (!f.isDirectory()) // 若非目录(即文件)，添加到pathList
					pathList.add(filePathString + f.getName());
			}
			return pathList;
		}
		return null;
	}

}
